const Router = require('koa-router');
const {db, Op,QueryTypes } = require("../../models/db");
const {xe} = require("../../tools/tool");
const router = new Router();
// 换算购物车saveSale
router.post('/app/saveCart', async ctx => {
    let usr = ctx.user
    let tenantId = usr.tenantId
    let cart = ctx.request.body.cart
    let buId = cart.buId
    let invId = cart.invId
    let unit = cart.unit
    let deduction = cart.deduction?xe.toNumber(cart.deduction):0
    let send = cart.send?cart.send:''
    let remark = cart.remark?cart.remark:''
    if(buId && cart.invId) {
        let cartModel = db.models['cart'].build()
        cartModel.tenantId = tenantId
        cartModel.uid = usr.id
        cartModel.buId = buId
        cartModel.invId = invId
        cartModel.unit = unit
        cartModel.qty = cart.qty
        cartModel.amount = cart.amount
        cartModel.deduction = deduction
        cartModel.send = send
        cartModel.price = xe.toNumber(cart.price)
        cartModel.remark = remark
        await cartModel.save()
    }

    return ctx.suc('')
})
router.post('/app/altCart', async ctx => {
    let usr = ctx.user
    let tenantId = usr.tenantId
    let cart = ctx.request.body.cart
    let cartId = cart.cartId
    let buId = cart.buId
    let invId = cart.invId
    let unit = cart.unit
    let deduction = cart.deduction?xe.toNumber(cart.deduction):0
    let send = cart.send?cart.send:''
    let remark = cart.remark?cart.remark:''
    if(buId && cart.invId && cart.cartId) {
        let cartModel = await db.models['cart'].findOne({
            where: {
                tenantId,
                id: cartId
            }
        })
        cartModel.tenantId = tenantId
        cartModel.uid = usr.id
        cartModel.buId = buId
        cartModel.invId = invId
        cartModel.unit = unit
        cartModel.qty = cart.qty
        cartModel.amount = cart.amount
        cartModel.deduction = deduction
        cartModel.send = send
        cartModel.price = xe.toNumber(cart.price)
        cartModel.remark = remark
        await cartModel.save()
    }

    return ctx.suc('')
})

module.exports = router;
